/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.account.controller.admin;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.Refunds;
import com.rzico.account.entity.Transfer;
import com.rzico.account.model.Attach;
import com.rzico.account.service.PaymentService;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysPvuvTravel;
import com.rzico.core.entity.SysUser;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.core.service.SysPluginService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

/**
 * 收款单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "收款单接口")
@RestController
@RequestMapping("/admin/payment")
public class PaymentAdminController extends BaseController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private SysPluginService sysPluginService;

    @Autowired
    private SysSequenceService sysSequenceService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 收款统计
     *
     * @return
     */
    @ApiOperation("收款统计")
    @GetMapping("/summary")
    @ApiImplicitParams({@ApiImplicitParam(name = "days", value = "统计天数0为当前，近7天为6", dataType = "Integer", allowMultiple = true, paramType = "query")})
    public CommResult<SysPvuvTravel> summary(Integer days) {
        Map<String, Object> params = new HashMap<String, Object>();
        Enterprise enterprise = enterpriseService.getCurrent();
        params.put("enterpriseId", enterprise.getId());
        params.put("startDate", DateUtils.truncate(DateUtils.addDays(new Date(),-days), Calendar.DATE));
        params.put("endDate", new Date());

        List<Map<String,Object>> data = paymentService.summary(params);
        return CommResult.success(data);
    }

    /**
     * 分页查询收款单
     *
     * @return
    */
    @ApiOperation("分页查询收款单")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "orderSn", value = "订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sn", value = "付款单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "memberId", value = "客户Id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态 {0:等待支付,1:支付成功,2.超时关闭,3:支付失败}", dataType = "Long", paramType = "query")
    })
    public CommResult<Payment> list(Date startDate, Date endDate,Long memberId,String sn,String orderSn,Integer status, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
            params.put("startDate",DateUtils.truncate(startDate, Calendar.DATE));
        }
        if (endDate!=null){
            params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        if (memberId!=null){
            params.put("memberId",memberId);
        } else {
            Enterprise enterprise = enterpriseService.getCurrent();
            if (enterprise!=null) {
                params.put("enterpriseId", enterprise.getId());
            } else {
                return CommResult.error("没有开通企业");
            }
        }

        if (status!=null){
            params.put("status",status);
        }

        if (StringUtils.isNotEmpty(orderSn)){
            params.put("orderSn", orderSn);
        }
        if (StringUtils.isNotEmpty(sn)){
            params.put("sn", sn);
        }


        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Payment> list = paymentService.selectList(params);
        PageResult<Payment> pageResult = new PageResult<Payment>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条收款单
     *
     * @return
    */
    @ApiOperation("查询单条收款单")
    @GetMapping("/find/{id}")
    public CommResult<Payment> find(@PathVariable String id) {
        Payment result = paymentService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("payment",result);

        Map<String,Object> params = new HashMap<>();
        String sn = result.getSn();
        String [] sns = sn.split("-");
        params.put("groupSn",sns[0]);

        List<Payment> payments = paymentService.selectList(params);

        data.put("itemList",payments);

        return CommResult.success(data);

    }

    /**
     * 保存收款单
     *
     * @param list
     * @return
     */
    @ApiOperation("保存收款单")
    @PostMapping("/save")
    public CommResult<Payment> save(@RequestBody List<Payment> list) {
        logger.info(">>>>>>>>>>>>>>>>>>保存收款单 start<<<<<<<<<<<<<<<<<<<<");
        if (null == list || list.size() == 0){
            return CommResult.error("收款单明细为空");
        }
        logger.info("保存收款单传参: [{}]", list.toString());
        String errMsg = "";
        for (Payment payment : list){
            if (null == payment.getAmount() || payment.getAmount().compareTo(BigDecimal.ZERO)==0){
                errMsg = "收款金额为空或者0";
                break;
            }
            if (StringUtils.isEmpty(payment.getPaymentPluginId())){
                errMsg = "支付方式为空";
                break;
            }
            if (null == payment.getMemberId()){
                errMsg = "收款会员为空";
                break;
            }
            if (null == payment.getReceivableId()){
                errMsg = "应收款ID为空";
                break;
            }
            if (payment.getSn()==null) {
                payment.setSn(sysSequenceService.generate("payment"));
            }
            if (payment.getQuantity()==null) {
                payment.setQuantity(BigDecimal.ZERO);
            }
            if (null == payment.getFee()) {
                payment.setFee(BigDecimal.ZERO);
            }
        }
        if (StringUtils.isNotEmpty(errMsg)){
            return CommResult.error(errMsg);
        }
        try {
            int affectCount = paymentService.insert(list);
            if (affectCount <= 0) {
                return CommResult.error();
            }
        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }
        return CommResult.success();

    }


//    /**
//     * 收款单确认
//     */
//    @ApiOperation("收款单确认")
//    @PostMapping("/confirm/{id}")
//    public CommResult<Payment> confirm(@PathVariable Long id) {
//
//        Assert.notNull(id, "付款单号为空");
//        int affectCount = paymentService.confirm(id);
//        if (affectCount <= 0){
//            return CommResult.error();
//        }
//
//        Payment result = paymentService.findById(id);
//        return CommResult.success(result);
//
//    }

    /**
     * 收款单取消
     *
     * @param id
     * @return
     */
/*    @ApiOperation("收款单取消")
    @PostMapping("/cancel/{id}")
    public CommResult<Payment> cancel(@PathVariable Long id) {
        Assert.notNull(id, "付款单号为空");

        int affectCount = paymentService.cancel(id);
        if (affectCount <= 0){
            return CommResult.error();
        }

        Payment result = paymentService.findById(id);
        return CommResult.success(result);

    }*/

    /**
     * 批量删除收款单
     *
     * @param ids
     * @return
     */
 //   @Log(desc = "批量删除收款单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除收款单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Payment> del(@PathVariable String ids) {

        paymentService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新收款单
     *
     * @param payments
     * @return
     */
  //  @Log(desc = "更新收款单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新收款单")
    @PostMapping("/update")
    public CommResult<Payment> update(@RequestBody List<Payment> payments) {
        for (Payment payment : payments){
            if (StringUtils.isEmpty(payment.getPaymentPluginId())){
                return CommResult.error("支付方式为空");
            }
            if (null == payment.getMemberId()){
                return CommResult.error("收款会员为空");
            }
            if (null == payment.getReceivableId()){
                //TODO
            }
            if (payment.getSn()==null) {
                payment.setSn(sysSequenceService.generate("payment"));
            }
            if (null == payment.getFee()) {
                payment.setFee(BigDecimal.ZERO);
            }
            if (payment.getQuantity()==null) {
                payment.setQuantity(BigDecimal.ZERO);
            }
            if (payment.getStatus()==null) {
                payment.setStatus(0);
            }
        }
        int affectCount = paymentService.update(payments);
        if (affectCount <= 0){
            return CommResult.error();
        }
        return CommResult.success("更新成功");
    }


    /**
     * 对账
     *
     * @param id
     * @return
     */
 //   @Log(desc = "对账", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("对账")
    @PostMapping("/query")
    public CommResult<Payment> query(Long id) {
        Payment payment = paymentService.findById(id);
        if (payment.getPaymentPluginId()==null) {
            return CommResult.error("没有付款");
        }

        PaymentPlugin paymentPlugin = sysPluginService.getPaymentPlugin(payment.getPaymentPluginId());

        Enterprise enterprise = enterpriseService.findById(payment.getEnterpriseId());

        SysPlugin sysPlugin = sysPluginService.findByPlugin(enterprise.getMchId(),payment.getPaymentPluginId());
        if (sysPlugin==null) {
            return CommResult.error("无效插件编号");
        }
        Map<String,Object> resultMap = paymentPlugin.tradeQuery(sysPlugin,payment.getSn(),payment.getTranSn(),null);

        if ("0000".equals(resultMap.get("return_code").toString())) {
            try {
                paymentService.handle(payment.getSn(),resultMap.get("tranSn").toString());
                return CommResult.success(payment);
            } catch (Exception e) {
                return CommResult.error("付款通知失败");
            }
        } else {
            if (!"0001".equals(resultMap.get("return_code").toString()) && !"9999".equals(resultMap.get("return_code").toString()) ) {
//                if (resultMap.get("error_msg")!=null) {
//                    payment.setTranSn(resultMap.get("error_msg").toString());
//                } else {
//                    payment.setTranSn("未知错误");
//                }
                payment.setStatus(Refunds.STATUS_FAILURE);
                paymentService.updateByPrimaryKeySelective(payment);
            }
            return CommResult.error(resultMap.get("err_msg").toString());
        }

    }

    /**
     * 发起退款
     *
     * @param id
     * @return
     */
  //  @Log(desc = "发起退款", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("发起退款")
    @PostMapping("/refund")
    public CommResult<Payment> refund(Long id) {
        Payment payment = paymentService.findById(id);
        if (payment.getPaymentPluginId()==null) {
            return CommResult.error("没有付款");
        }

        if (!payment.getStatus().equals(Payment.STATUS_SUCCESS)) {
            return CommResult.error("付款状态才能退款");
        }

        BigDecimal amount = payment.getAmount().subtract(payment.getRefund());
        if (amount.compareTo(BigDecimal.ZERO)<=0) {
            return CommResult.error("不能重复退款");
        }

        try {

            List<Refunds> refundsList = paymentService.refund(id, sysSequenceService.generate("refunds"));

            for (Refunds refunds:refundsList) {
                //TODO发送退款通知
                Attach attachQueue = new Attach();
                attachQueue.setCode("0000");
                attachQueue.setId(String.valueOf(refunds.getId()));
                attachQueue.setQueue("queue.refunds.submit");
                Message message = MessageBuilder
                        .withBody(JSON.toJSONString(attachQueue).getBytes())
                        .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                        .build();
                CorrelationData correlationData = new CorrelationData();
                correlationData.setId(UUID.randomUUID().toString());
                logger.info("发送 MQ");
                rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);

            }

        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }

        payment = paymentService.findById(id);
        return CommResult.success(payment);

    }

}
